package com.wocai.jrt.orgadmin.employee.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vteba.common.exception.ServiceException;
import com.vteba.service.generic.impl.MyBatisServiceImpl;
import com.vteba.tx.jdbc.mybatis.spi.BaseDao;
import com.vteba.tx.jdbc.sequence.HexademicalKeyGenerator;
import com.vteba.utils.id.ObjectId;
import com.vteba.utils.json.FastJsonUtils;
import com.wocai.jrt.admin.common.bean.Icon;
import com.wocai.jrt.admin.common.bean.State;
import com.wocai.jrt.im.ImSdk;
import com.wocai.jrt.orgadmin.customer.model.Customer;
import com.wocai.jrt.orgadmin.customer.service.spi.CustomerService;
import com.wocai.jrt.orgadmin.employee.bean.EmpGroupTreeBean;
import com.wocai.jrt.orgadmin.employee.bean.EmployeeGroupReqBean;
import com.wocai.jrt.orgadmin.employee.bean.EmployeeListReqBean;
import com.wocai.jrt.orgadmin.employee.dao.EmployeeDao;
import com.wocai.jrt.orgadmin.employee.dao.EmployeeGroupDao;
import com.wocai.jrt.orgadmin.employee.model.Employee;
import com.wocai.jrt.orgadmin.employee.model.EmployeeGroup;
import com.wocai.jrt.orgadmin.employee.model.EmployeeGroupBean;
import com.wocai.jrt.orgadmin.employee.model.GroupMember;
import com.wocai.jrt.orgadmin.employee.model.GroupProduct;
import com.wocai.jrt.orgadmin.employee.model.Org;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeGroupService;
import com.wocai.jrt.orgadmin.employee.service.spi.GroupMemberService;
import com.wocai.jrt.orgadmin.employee.service.spi.GroupProductService;
import com.wocai.jrt.orgadmin.employee.service.spi.OrgService;
import com.wocai.jrt.orgadmin.investor.bean.EmpBreifBean;
import com.wocai.jrt.orgadmin.investor.model.Investor;
import com.wocai.jrt.orgadmin.investor.service.spi.InvestorService;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.setting.model.Setting;
import com.wocai.jrt.orgadmin.setting.service.spi.SettingService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 理财团队相关的service业务实现。
 * 
 * @author yinlei
 * @date 2015-8-17 19:59:25
 */
@Named
public class EmployeeGroupServiceImpl extends
		MyBatisServiceImpl<EmployeeGroup, EmployeeGroupBean, String> implements
		EmployeeGroupService {
	private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeGroupServiceImpl.class);
	// 添加了方法后，记得改为private
	protected EmployeeGroupDao employeeGroupDao;

	@Inject
	private GroupProductService groupProductServiceImpl;
	@Inject
	private ProductService productServiceImpl;
	@Inject
	private GroupMemberService groupMemberServiceImpl;
	@Inject
	private EmployeeDao employeeDao;
	@Inject
	private OrgService orgServiceImpl;
	@Inject
	private InvestorService investorServiceImpl;
	@Inject
	private HexademicalKeyGenerator hexademicalKeyGenerator;
	@Inject
	private CustomerService customerServiceImpl;
	@Inject
	private SettingService settingServiceImpl;

	@Override
	@Inject
	public void setBaseDao(BaseDao<EmployeeGroup, EmployeeGroupBean, String> employeeGroupDao) {
		this.baseDao = employeeGroupDao;
		this.employeeGroupDao = (EmployeeGroupDao) employeeGroupDao;
	}

	private List<EmpGroupTreeBean> empGroupBeans;
	
	private List<EmpGroupTreeBean> empGroupBeansEmp;

	/**
	 * 获取机构下理财师团队tree
	 * 
	 * @param String
	 *            orgId
	 * @return List<EmpGroupTreeBean>
	 */
	@Override
	public EmpGroupTreeBean tree(String orgId) {
		EmpGroupTreeBean root = new EmpGroupTreeBean();
		try {
			EmployeeGroup employeeGroup = employeeGroupDao.get(orgId);
			// 获取机构下所有理财师列表
			empGroupBeans = employeeGroupDao.getEmpGroupList(orgId);
			root.setId(employeeGroup.getId());
			root.setText(employeeGroup.getGroupName());
			root.setEmployeeId(employeeGroup.getEmployeeId());
			root.setEmployeeName(employeeGroup.getEmployeeName());
			root.setChildren(recursiveTree(employeeGroup.getId()));
			State state = new State();
			state.setOpened(true);
			state.setLoaded(true);
			state.setSelected(true);
			root.setState(state);
			root.setIcon(Icon.FOLDER_DANGER);
		} catch (Exception e) {
			LOGGER.error("get resource tree error, errorMsg=[{}].", e.getMessage());
		}
		return root;
	}

	/**
	 * 递归算法解析成树形结构
	 * 
	 * @param id
	 * @return List<EmpGroupTreeBean>
	 */
	public List<EmpGroupTreeBean> recursiveTree(String id) {
		// 查询所有root节点
		List<EmpGroupTreeBean> childTreeNodes = queryTreeNode(id);
		// 遍历所有root节点下的子节点
		for (EmpGroupTreeBean child : childTreeNodes) {
			List<EmpGroupTreeBean> list1 = recursiveTree(child.getId());
			child.setChildren(list1);
			State state = new State();
			state.setOpened(true);
			state.setLoaded(true);
			child.setState(state);
			if (child.getPlannerGroup()) {
				child.setIcon(Icon.BRIEF_DANGER);
			} else {
				child.setIcon(Icon.FOLDER_DANGER);
			}
		}
		return childTreeNodes;
	}

	public List<EmpGroupTreeBean> queryTreeNode(String id) {
		List<EmpGroupTreeBean> empList = new ArrayList<EmpGroupTreeBean>();
		for (EmpGroupTreeBean emp : empGroupBeans) {
			if (null != emp.getParent() && emp.getParent().equals(id)) {
				empList.add(emp);
			}
		}
		return empList;
	}

	@Override
	public EmpGroupTreeBean empTree(String empGroupId) {
		EmpGroupTreeBean root = new EmpGroupTreeBean();
		EmployeeGroup employeeGroup = employeeGroupDao.get(empGroupId);
		root.setId(employeeGroup.getEmployeeId());
		root.setText(employeeGroup.getEmployeeName());
		State state = new State();
		state.setOpened(false);
		state.setLoaded(true);
		root.setState(state);
		root.setIcon(Icon.FILE_DANGER);

		List<Employee> employeeList = employeeGroupDao.getEmployeeGroupList(empGroupId);
		List<EmpGroupTreeBean> empList = new ArrayList<EmpGroupTreeBean>();
		for (Employee employee : employeeList) {
			EmpGroupTreeBean treeBean = new EmpGroupTreeBean();
			treeBean.setId(employee.getEmployeeId());
			treeBean.setText(employee.getName());
			State state2 = new State();
			state2.setOpened(false);
			state2.setLoaded(true);
			root.setState(state2);
			treeBean.setIcon(Icon.FILE_DANGER);
			empList.add(treeBean);
		}
		root.setChildren(empList);
		return root;
	}

	/**
	 * 递归算法删除团队
	 * 
	 */
	@Override
	public int deleteGroup(String groupId) {
		int i = 0;
		try {
			// 软删除该节点
			EmployeeGroup delEmployeeGroup = employeeGroupDao.get(groupId);
			delEmployeeGroup.setDeleted(true);
			i = employeeGroupDao.updateById(delEmployeeGroup);
			// 删除该部门所有的人
			GroupMember groupMember = new GroupMember();
			groupMember.setGroupId(groupId);
			groupMemberServiceImpl.deleteBulks(groupMember);
			// 修改该部门的员工信息
			Employee odlEmployee = new Employee();
			odlEmployee.setDeptId(groupId);
			Employee newEmployee = new Employee();
			newEmployee.setDeptId("");
			newEmployee.setDepartment("");
			employeeDao.updateBulks(newEmployee, odlEmployee);
			// 找出该节点下所有节点
			EmployeeGroup employeeGroup = new EmployeeGroup();
			employeeGroup.setParent(groupId);
			List<EmployeeGroup> employeeGroupList = employeeGroupDao.queryList(employeeGroup);

			// 软删除
			for (EmployeeGroup employeeGroup2 : employeeGroupList) {
				if (employeeGroup2 != null) {
					int j = deleteGroup(employeeGroup2.getId());
					// 用于判断有没有删除成功
					if (j < i) {
						i = j;
					}
				}
			}
		} catch (Exception e) {
			throw new ServiceException("删除部门出错！",e);
			//LOGGER.error("deleteGroup error, errorMsg=[{}].", e.getMessage());
		}
		return i;
	}

	@Override
	public int addGroup(EmployeeGroupReqBean model) {
		int i = 0;
		try {
			if (model.getPlannerGroup()) {// 是理财师团队
				// employee_group表添加一条字段
				EmployeeGroup employeeGroup = new EmployeeGroup();
				employeeGroup.setId(ObjectId.get().toString());
				employeeGroup.setGroupName(model.getGroupName());
				employeeGroup.setEmployeeId(model.getEmployeeId());
				employeeGroup.setEmployeeName(model.getEmployeeName());
				employeeGroup.setInvestorNumber(0);
				employeeGroup.setMemberNumber(1);
				employeeGroup.setOrgId(model.getOrgId());
				employeeGroup.setParent(model.getParent());
				employeeGroup.setSaleAll(model.getSaleAll());
				employeeGroup.setPlannerGroup(true);
				int productNum = model.getSaleProduct().size();
				if (productNum > 0 && !model.getSaleAll()) {
					employeeGroup.setProductNumber(productNum);
					// group_product表把可售产品加进去
					for (Product product : model.getSaleProduct()) {
						product = productServiceImpl.get(product.getId());
						if (null != product) {
							GroupProduct groupProduct = new GroupProduct();
							groupProduct.setId(ObjectId.get().toString());
							groupProduct.setGroupId(employeeGroup.getId());
							groupProduct.setProductId(product.getId());
							groupProduct.setProductName(product.getProductName());
							groupProduct.setProductCode(product.getProductCode());
							groupProduct.setBriefName(product.getBriefName());
							groupProduct.setType(product.getType());
							groupProduct.setOrgId(product.getOrgId());
							groupProduct.setCreateTime(new Date());
							int j = groupProductServiceImpl.save(groupProduct);
							if (j < i) {
								i = j;
							}
						}
					}
				}
				i = employeeGroupDao.save(employeeGroup);
				// 更新group_member表
				GroupMember oldGroupMember = new GroupMember();
				oldGroupMember.setEmployeeId(model.getEmployeeId());
				oldGroupMember = groupMemberServiceImpl.unique(oldGroupMember);
				if (oldGroupMember == null) {// 之前没有部门
					GroupMember groupMember = new GroupMember();
					groupMember.setGroupId(employeeGroup.getId());
					groupMember.setEmployeeId(employeeGroup.getEmployeeId());
					groupMember.setId(ObjectId.get().toString());
					int k = groupMemberServiceImpl.save(groupMember);
					if (k < i) {
						i = k;
					}
				} else {// 之前有部门
					// 更新employee_group表，将部门人数减一
					EmployeeGroup oldEmployeeGroup = employeeGroupDao.get(oldGroupMember
							.getGroupId());
					if (oldEmployeeGroup != null) {
						oldEmployeeGroup.setMemberNumber(oldEmployeeGroup.getMemberNumber() - 1);
					}
					employeeGroupDao.updateById(oldEmployeeGroup);
					// 更新group_member
					oldGroupMember.setGroupId(employeeGroup.getId());
					int k = groupMemberServiceImpl.updateById(oldGroupMember);
					if (k < i) {
						i = k;
					}
				}

				// 更新自己的部门
				Employee employee = new Employee();
				employee.setEmployeeId(model.getEmployeeId());
				employee.setDeptId(employeeGroup.getId());
				employee.setDepartment(employeeGroup.getGroupName());
				int l = employeeDao.updateById(employee);
				if (l < i) {
					i = l;
				}
			} else {// 不是理财师团队
				// employee_group表添加一条字段
				EmployeeGroup employeeGroup = new EmployeeGroup();
				employeeGroup.setId(ObjectId.get().toString());
				employeeGroup.setGroupName(model.getGroupName());
				employeeGroup.setEmployeeId(model.getEmployeeId());
				employeeGroup.setEmployeeName(model.getEmployeeName());
				employeeGroup.setInvestorNumber(0);
				employeeGroup.setMemberNumber(0);
				employeeGroup.setOrgId(model.getOrgId());
				employeeGroup.setParent(model.getParent());
				employeeGroup.setSaleAll(false);// 不能卖产品
				employeeGroup.setPlannerGroup(false);
				i = employeeGroupDao.save(employeeGroup);
				if (model.getEmployeeId() != null) {// 有负责人时更新负责人
					// 更新group_member表
					GroupMember oldGroupMember = new GroupMember();
					oldGroupMember.setEmployeeId(model.getEmployeeId());
					oldGroupMember = groupMemberServiceImpl.unique(oldGroupMember);
					if (oldGroupMember == null) {// 之前没有部门
						GroupMember groupMember = new GroupMember();
						groupMember.setGroupId(employeeGroup.getId());
						groupMember.setEmployeeId(employeeGroup.getEmployeeId());
						groupMember.setId(ObjectId.get().toString());
						int k = groupMemberServiceImpl.save(groupMember);
						if (k < i) {
							i = k;
						}
					} else {// 之前有部门
						// 更新employee_group表，将部门人数减一
						EmployeeGroup oldEmployeeGroup = employeeGroupDao.get(oldGroupMember
								.getGroupId());
						if (oldEmployeeGroup != null) {
							oldEmployeeGroup
									.setMemberNumber(oldEmployeeGroup.getMemberNumber() - 1);
						}
						employeeGroupDao.updateById(oldEmployeeGroup);
						// 更新group_member
						oldGroupMember.setGroupId(employeeGroup.getId());
						int k = groupMemberServiceImpl.updateById(oldGroupMember);
						if (k < i) {
							i = k;
						}
					}
					// 更新自己的部门
					Employee employee = new Employee();
					employee.setEmployeeId(model.getEmployeeId());
					employee.setDeptId(employeeGroup.getId());
					employee.setDepartment(employeeGroup.getGroupName());
					int l = employeeDao.updateById(employee);
					if (l < i) {
						i = l;
					}
				}
			}
		} catch (Exception e) {
			throw new ServiceException("天机部门出错！",e);
//			i = 0;
//			LOGGER.error("addGroup error, errorMsg=[{}].", e.getMessage());
		}
		return i;
	}

	@Override
	public int updateGroupById(EmployeeGroupReqBean model) {
		int result = 0;
		try {
			String departmentId = model.getParent();// 要更新的部门信息
			String newEmployeeId = model.getEmployeeId();// 部门的新负责人
			EmployeeGroup oldEmployeeGroup = employeeGroupDao.get(departmentId);
			if (oldEmployeeGroup == null) {
				result = 2;// 部门不存在
				return result;
			}
			// 更新部门下每个人的信息
			if (null != model.getGroupName()) {
				if (!(model.getGroupName().equals(oldEmployeeGroup.getGroupName()))) {
					Employee oldparam = new Employee();
					oldparam.setDeptId(departmentId);

					Employee newparam = new Employee();
					newparam.setDepartment(model.getGroupName());
					employeeDao.updateBulks(newparam, oldparam);
				}
			}
			// 更新部门负责人
			if (newEmployeeId != null) {
				Employee newEmployee = employeeDao.get(newEmployeeId);
				if (newEmployee == null) {
					result = 3;// 部门负责人不存在
					return result;
				}
				if (newEmployee.getState() == 0) {
					result = 4;// 部门负责人已离职
					return result;
				}
				EmployeeGroup employeeGroupTest = new EmployeeGroup();
				employeeGroupTest.setEmployeeId(newEmployeeId);
				employeeGroupTest.setDeleted(false);
				List<EmployeeGroup> employeeGroupList = employeeGroupDao
						.queryList(employeeGroupTest);
				if (employeeGroupList.size() >= 1) {
					result = 5;// 部门负责人不能同时负责多个部门
					return result;
				}
				// 删除旧GroupMember
				GroupMember groupMember = new GroupMember();
				groupMember.setEmployeeId(oldEmployeeGroup.getEmployeeId());
				groupMemberServiceImpl.deleteBulks(groupMember);

				// 删除新GroupMember
				GroupMember newgroupMember = new GroupMember();
				newgroupMember.setEmployeeId(newEmployeeId);
				groupMemberServiceImpl.deleteBulks(newgroupMember);

				// 更新employee表，旧队长的信息干掉
				Employee oldEmployee = new Employee();
				oldEmployee.setEmployeeId(oldEmployeeGroup.getEmployeeId());
				oldEmployee.setDepartment("");
				oldEmployee.setDeptId("");
				employeeDao.updateById(oldEmployee);

				// 更新group_member表，添加一个队员
				GroupMember newGroupMember = new GroupMember();
				newGroupMember.setGroupId(departmentId);
				newGroupMember.setEmployeeId(newEmployeeId);
				newGroupMember.setId(ObjectId.get().toString());
				groupMemberServiceImpl.save(newGroupMember);

				// 更新employee表，新队长的信息添加
				Employee newUpdataEmployee = new Employee();
				newUpdataEmployee.setEmployeeId(newEmployeeId);
				newUpdataEmployee.setDepartment(model.getGroupName() == null ? oldEmployeeGroup
						.getGroupName() : model.getGroupName());
				newUpdataEmployee.setDeptId(departmentId);
				employeeDao.updateById(newUpdataEmployee);

				//
				// int i, j, k;
				// if (oldGroupMember == null) {
				// // 更新employee表，旧队长的信息干掉
				// Employee oldEmployee = new Employee();
				// oldEmployee.setEmployeeId(oldEmployeeGroup.getEmployeeId());
				// oldEmployee.setDepartment("");
				// oldEmployee.setDeptId("");
				// i = employeeServiceImpl.updateById(oldEmployee);
				// // 更新group_member表，添加一个队员
				// GroupMember newGroupMember = new GroupMember();
				// newGroupMember.setGroupId(model.getParent());
				// newGroupMember.setEmployeeId(newEmployeeId);
				// newGroupMember.setId(ObjectId.get().toString());
				// j = groupMemberServiceImpl.save(newGroupMember);
				// // 更新employee表，新队长的信息添加
				// Employee newUpdataEmployee = new Employee();
				// newUpdataEmployee.setEmployeeId(newEmployee.getEmployeeId());
				// newUpdataEmployee.setDepartment(model.getGroupName() == null
				// ? oldEmployeeGroup
				// .getGroupName() : model.getGroupName());
				// newUpdataEmployee.setDeptId(departmentId);
				// k = employeeServiceImpl.updateById(newUpdataEmployee);
				// } else {
				// // 更新employee表，旧队长的信息干掉
				// Employee oldEmployee = new Employee();
				// oldEmployee.setEmployeeId(oldEmployeeGroup.getEmployeeId());
				// oldEmployee.setDepartment("");
				// oldEmployee.setDeptId("");
				// i = employeeServiceImpl.updateById(oldEmployee);
				// // 更新group_member表，换一个队员
				// GroupMember oldUpdataGroupMember = new GroupMember();
				// oldUpdataGroupMember.setId(oldGroupMember.getId());
				// oldUpdataGroupMember.setEmployeeId(newEmployee.getId());
				// j = groupMemberServiceImpl.updateById(oldUpdataGroupMember);
				// // 更新employee表，新队长的信息添加
				// Employee newUpdataEmployee = new Employee();
				// newUpdataEmployee.setEmployeeId(newEmployee.getEmployeeId());
				// newUpdataEmployee.setDepartment(model.getGroupName() == null
				// ? oldEmployeeGroup
				// .getGroupName() : model.getGroupName());
				// newUpdataEmployee.setDeptId(departmentId);
				// k = employeeServiceImpl.updateById(newUpdataEmployee);
				// }
				// if (!(i == 1 && j == 1 && k == 1)) {
				// LOGGER.warn("updateGroupById update newEmployeeId warn");
				// }
			}
			// 更新部门信息
			EmployeeGroup employeeGroup = new EmployeeGroup();
			employeeGroup.setId(departmentId);
			employeeGroup.setEmployeeId(model.getEmployeeId());
			employeeGroup.setEmployeeName(model.getEmployeeName());
			employeeGroup.setGroupName(model.getGroupName());
			employeeGroup.setSaleAll(model.getSaleAll());
			employeeGroup.setProductNumber(model.getSaleProduct().size());
			int i = employeeGroupDao.updateById(employeeGroup);
			if (i == 1) {
				result = 1;
			} else {
				LOGGER.error("updateGroupById error EmployeeGroup error");
				result = 0;
			}
			// 更新部门可售产品
			GroupProduct paramT = new GroupProduct();
			paramT.setGroupId(employeeGroup.getId());
			int j = groupProductServiceImpl.deleteBulks(paramT);
			if (j < 1) {
				LOGGER.warn("updateGroupById update GroupProduct warn");
			}
			int productNum = model.getSaleProduct().size();
			if (productNum > 0 && !model.getSaleAll()) {
				// group_product表把可售产品加进去
				for (Product product : model.getSaleProduct()) {
					product = productServiceImpl.get(product.getId());
					if (null != product) {
						GroupProduct groupProduct = new GroupProduct();
						groupProduct.setId(ObjectId.get().toString());
						groupProduct.setGroupId(employeeGroup.getId());
						groupProduct.setProductId(product.getId());
						groupProduct.setProductName(product.getProductName());
						groupProduct.setProductCode(product.getProductCode());
						groupProduct.setBriefName(product.getBriefName());
						groupProduct.setType(product.getType());
						groupProduct.setOrgId(product.getOrgId());
						groupProduct.setCreateTime(new Date());
						int k = groupProductServiceImpl.save(groupProduct);
						if (k < 1) {
							LOGGER.warn("updateGroupById update GroupProduct warn");
						}
					}
				}
			}
		} catch (Exception e) {
			throw new ServiceException("更新部门出错！",e);
			//LOGGER.error("deleteGroup error, errorMsg=[{}].", e.getMessage());
			//result = 0;
		}
		return result;
	}

	@Override
	public List<EmpBreifBean> getEmployeeNotGroup(String employeeKey) {
		EmployeeListReqBean employeeListReqBean = new EmployeeListReqBean();
		employeeListReqBean.setKey(employeeKey);
		employeeListReqBean.setOrgId(UserUtils.getOrgId());
		return employeeGroupDao.getOrgEmployeeList(employeeListReqBean);
	}

	@Override
	public EmpGroupTreeBean plannerTree(String orgId) {
		// 获取机构下所有理财师列表
		EmployeeGroup employeeGroup = new EmployeeGroup();
		employeeGroup.setOrgId(orgId);
		employeeGroup.setPlannerGroup(true);
		employeeGroup.setDeleted(false);
		List<EmployeeGroup> employeeGroupList = employeeGroupDao.queryList(employeeGroup);
		List<EmpGroupTreeBean> childrenList = new ArrayList<EmpGroupTreeBean>();
		for (EmployeeGroup employeeGroup2 : employeeGroupList) {
			EmpGroupTreeBean children = new EmpGroupTreeBean();
			children.setId(employeeGroup2.getId());
			children.setText(employeeGroup2.getGroupName());
			State state = new State();
			state.setOpened(true);
			state.setLoaded(true);
			state.setSelected(true);
			children.setState(state);
			children.setIcon(Icon.FILE_DANGER);
			childrenList.add(children);
		}
		EmpGroupTreeBean root = new EmpGroupTreeBean();
		root.setId("root");
		root.setText("所有理财师团队");
		root.setChildren(childrenList);
		State state = new State();
		state.setOpened(true);
		state.setLoaded(true);
		root.setState(state);
		root.setIcon(Icon.FILE_DANGER);
		return root;
	}

	@Override
	public int empGroupScript() {
		int i = 0;
		try {
			Org org = new Org();
			List<Org> orgList = orgServiceImpl.queryList(org);
			for (Org orgUpdata : orgList) {
				// 删除机构下的旧部门结构
				EmployeeGroup deleEmployeeGroup = new EmployeeGroup();
				deleEmployeeGroup.setOrgId(orgUpdata.getId());
				employeeGroupDao.deleteBulks(deleEmployeeGroup);
				// 为机构添加一个新的全公司部门
				EmployeeGroup insertEmployeeGroup = new EmployeeGroup();
				insertEmployeeGroup.setId(orgUpdata.getId());
				insertEmployeeGroup.setGroupName("全公司");
				insertEmployeeGroup.setPlannerGroup(false);
				insertEmployeeGroup.setSaleAll(false);
				insertEmployeeGroup.setOrgId(orgUpdata.getId());
				insertEmployeeGroup.setParent("root");
				insertEmployeeGroup.setMemberNumber(1);
				employeeGroupDao.save(insertEmployeeGroup);
				// 更新机构下每个员工的部门信息
				Employee employeeQuery = new Employee();
				employeeQuery.setOrgId(orgUpdata.getId());
				employeeQuery.setState(1);
				List<Employee> employeeList = employeeDao.queryList(employeeQuery);
				employeeQuery.setState(0);
				List<Employee> employeeLeaveList = employeeDao.queryList(employeeQuery);
				// ------更新group_member
				for (Employee employeeUpdata : employeeList) {
					// 删除旧部门关系
					GroupMember groupMemberDel = new GroupMember();
					groupMemberDel.setEmployeeId(employeeUpdata.getId());
					groupMemberServiceImpl.deleteBulks(groupMemberDel);
					// 新加新部门关系
					GroupMember groupMemberUpdata = new GroupMember();
					groupMemberUpdata.setId(ObjectId.get().toString());
					groupMemberUpdata.setEmployeeId(employeeUpdata.getId());
					groupMemberUpdata.setGroupId(orgUpdata.getId());
					groupMemberServiceImpl.save(groupMemberUpdata);
					// 更新自己的部门信息
					Employee employee = new Employee();
					employee.setEmployeeId(employeeUpdata.getId());
					employee.setDepartment("全公司");
					employee.setDeptId(orgUpdata.getId());
					employeeDao.updateById(employee);
				}
				for (Employee employee : employeeLeaveList) {
					// 删除旧部门关系
					GroupMember groupMemberDel = new GroupMember();
					groupMemberDel.setEmployeeId(employee.getId());
					groupMemberServiceImpl.deleteBulks(groupMemberDel);
					// 更新自己的部门信息
					Employee employeeUp = new Employee();
					employeeUp.setEmployeeId(employee.getId());
					employeeUp.setDepartment("");
					employeeUp.setDeptId("");
					employeeDao.updateById(employee);
				}
			}
			i = 1;
		} catch (Exception e) {
			throw new ServiceException("重置部门失败！");
		}
		return i;
	}

	@Override
	public EmpGroupTreeBean plannerTreeNotSelect(String orgId) {
		// 获取机构下所有理财师列表
		EmployeeGroup employeeGroup = new EmployeeGroup();
		employeeGroup.setOrgId(orgId);
		employeeGroup.setPlannerGroup(true);
		employeeGroup.setDeleted(false);
		List<EmployeeGroup> employeeGroupList = employeeGroupDao.queryList(employeeGroup);
		List<EmpGroupTreeBean> childrenList = new ArrayList<EmpGroupTreeBean>();
		for (EmployeeGroup employeeGroup2 : employeeGroupList) {
			EmpGroupTreeBean children = new EmpGroupTreeBean();
			children.setId(employeeGroup2.getId());
			children.setText(employeeGroup2.getGroupName());
			State state = new State();
			state.setOpened(true);
			state.setLoaded(true);
			state.setSelected(false);
			children.setState(state);
			children.setIcon(Icon.FILE_DANGER);
			childrenList.add(children);
		}
		EmpGroupTreeBean root = new EmpGroupTreeBean();
		root.setId("root");
		root.setText("全公司");
		root.setChildren(childrenList);
		State state = new State();
		state.setOpened(true);
		state.setLoaded(true);
		root.setState(state);
		root.setIcon(Icon.FILE_DANGER);
		return root;
	}

	@Override
	public List<EmployeeGroup> getSelectedEmployeeGroup(EmployeeGroup employeeGroup) {
		return employeeGroupDao.getSelectedEmployeeGroup(employeeGroup);
	}

	@Override
	public int updateEmpGroupById(EmployeeGroup employeeGroup) {
		int result = 0;
		try {
			employeeGroupDao.updateById(employeeGroup);
			Employee oldEmployee = new Employee();
			oldEmployee.setDeptId(employeeGroup.getId());
			Employee newEmployee = new Employee();
			newEmployee.setDepartment(employeeGroup.getGroupName());
			employeeDao.updateBulks(newEmployee, oldEmployee);
			result = 1;
		} catch (Exception e) {
			throw new ServiceException("修改部门失败！");
		}
		return result;
	}

	@Override
	public EmpGroupTreeBean treeEmp(String orgId, String groupId) {
		EmpGroupTreeBean root = new EmpGroupTreeBean();
		try {
			EmployeeGroup employeeGroup = employeeGroupDao.get(orgId);
			// 获取机构下所有理财师列表
			empGroupBeansEmp = employeeGroupDao.getEmpGroupList(orgId);
			root.setId(employeeGroup.getId());
			root.setText(employeeGroup.getGroupName());
			root.setChildren(recursiveTreeEmp(employeeGroup.getId(),groupId));
			State state = new State();
			state.setOpened(true);
			state.setLoaded(true);
			if (employeeGroup.getId().equals(groupId)) {
				state.setSelected(true);
			} else {
				state.setSelected(false);
			}
			root.setState(state);
			root.setIcon(Icon.FOLDER_DANGER);
		} catch (Exception e) {
			LOGGER.error("get resource tree error, errorMsg=[{}].", e.getMessage());
		}
		return root;
	}
	
	public List<EmpGroupTreeBean> recursiveTreeEmp(String id,String groupId) {
		// 查询所有root节点
		List<EmpGroupTreeBean> childTreeNodes = queryTreeNodeEmp(id);
		// 遍历所有root节点下的子节点
		for (EmpGroupTreeBean child : childTreeNodes) {
			List<EmpGroupTreeBean> list1 = recursiveTreeEmp(child.getId(),groupId);
			child.setChildren(list1);
			State state = new State();
			state.setOpened(true);
			state.setLoaded(true);
			if (child.getId().equals(groupId)) {
				state.setSelected(true);
			} else {
				state.setSelected(false);
			}
			child.setState(state);
			if (child.getPlannerGroup()) {
				child.setIcon(Icon.BRIEF_DANGER);
			} else {
				child.setIcon(Icon.FOLDER_DANGER);
			}
		}
		return childTreeNodes;
	}
	
	public List<EmpGroupTreeBean> queryTreeNodeEmp(String id) {
		List<EmpGroupTreeBean> empList = new ArrayList<EmpGroupTreeBean>();
		for (EmpGroupTreeBean emp : empGroupBeansEmp) {
			if (null != emp.getParent() && emp.getParent().equals(id)) {
				empList.add(emp);
			}
		}
		return empList;
	}

	@Override
	public List<EmployeeGroup> getNoTeamLeaderGroup(EmployeeGroup employeeGroup) {
		return employeeGroupDao.getNoTeamLeaderGroup(employeeGroup);
	}

	@Override
	public int investorScript() {
		int i = 0;
		try {
			//找出所有的投资人
			Investor investor = new Investor();
			List<Investor> investorList = investorServiceImpl.queryList(investor);
			//更新每个投资人的邀请码
			for (Investor investor2 : investorList) {
				if (null == investor2.getInvitationCode()) {
					Investor investorUpdata = new Investor();
					investorUpdata.setId(investor2.getId());
					String invitationCode = hexademicalKeyGenerator.next();
					investorUpdata.setInvitationCode(invitationCode);
					investorServiceImpl.updateById(investorUpdata);
				} else if(investor2.getInvitationCode().length()<4){
					Investor investorUpdata = new Investor();
					investorUpdata.setId(investor2.getId());
					String invitationCode = hexademicalKeyGenerator.next();
					investorUpdata.setInvitationCode(invitationCode);
					investorServiceImpl.updateById(investorUpdata);
				}
			}
			i = 1;
		} catch (Exception e) {
			throw new ServiceException("更新错误！", e);
		}
		return i;
	}

	@Override
	public int imEggs() {
		int i = 0;
		try {
			//去腾讯注册IM账号 --Customer注册
			Customer customerQuery = new Customer();
			List<Customer> customers = customerServiceImpl.queryList(customerQuery);
			for (Customer customer : customers) {
				Map<String, String> imRegMap = new HashMap<String, String>();
				imRegMap.put("Identifier", customer.getId());
				imRegMap.put("Nick", customer.getName());
				imRegMap.put("FaceUrl", "");
				String api = "/v4/im_open_login_svc/account_import";
				String res = ImSdk.send(FastJsonUtils.toJson(imRegMap), api);
				LOGGER.info("新用户腾讯注册：[{}]", res);
			}
			//去腾讯注册IM账号 --Employee注册
			Employee employeeQuery = new Employee();
			List<Employee> employees = employeeDao.queryList(employeeQuery);
			for (Employee employee : employees) {
				Map<String, String> imRegMap = new HashMap<String, String>();
				imRegMap.put("Identifier", employee.getEmployeeId());
				imRegMap.put("Nick", employee.getName());
				imRegMap.put("FaceUrl", "");
				String api = "/v4/im_open_login_svc/account_import";
				String res = ImSdk.send(FastJsonUtils.toJson(imRegMap), api);
				LOGGER.info("新用户腾讯注册：[{}]", res);
			}
			
			//关联inverter与customer关联关系
			Investor investorQuery = new Investor();
			List<Investor> investors = investorServiceImpl.queryList(investorQuery);
			for (Investor investor : investors) {
				String mobile = investor.getMobile();
				if (!StringUtils.isBlank(mobile)) {
					Customer customer = new Customer();
					customer.setMobile(investor.getMobile());
					customer = customerServiceImpl.unique(customer);
					if (null != customer) {
						Investor investorUpdate = new Investor();
						investorUpdate.setId(investor.getId());
						investorUpdate.setCustomerId(customer.getId());
						investorServiceImpl.updateById(investorUpdate);
					}
				}
			}
			i = 1;
		} catch (Exception e) {
			throw new ServiceException("更新错误！", e);
		}
		return i;
	}

	@Override
	public int saveRevisitEggs() {
		Integer i = 0;
		try {
			Org org = new Org();
			org.setStart(null);
			List<Org> orgList = orgServiceImpl.queryList(org);  
			for (Org o : orgList) {
				Setting setting = new Setting();
				setting.setOrgId(o.getId());
				setting.setKeyName("orderRevisit");
				if (null == settingServiceImpl.unique(setting)) {
					setting.setId(ObjectId.get().toString());
					setting.setOrgId(o.getId());
					setting.setFlag(false);
					setting.setContent("是否需要开通订单回访");
					setting.setKeyName("orderRevisit");
					setting.setKeyValue("0");
					settingServiceImpl.save(setting);
					i++;
				} else {
					continue;
				}
			}
		} catch (ServiceException e) {
			throw new ServiceException("更新设置失败，",e);
		}
		return i;
	}
}
